from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet,ModelViewSet
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.decorators import list_route
from django_filters.rest_framework import DjangoFilterBackend
from accounts.filters import UserFilter
from .serializers import *
from .models import *
# Create your views here.
class ProductViewSet(ReadOnlyModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

class ShopCartViewSet(ModelViewSet):
    queryset = ShopCart.objects.all()
    serializer_class = ShopCartSerializer
    permission_classes = (permissions.IsAuthenticated,)
    filter_backends = (UserFilter, DjangoFilterBackend,)
    filter_fields = ('checked',)

class ShopOrderViewSet(ModelViewSet):
    queryset = ShopOrder.objects.all()
    serializer_class = ShopOrderOutSerializer
    # permission_classes = (permissions.IsAuthenticated,)
    filter_backends = (UserFilter,DjangoFilterBackend,)
    filter_fields=('addr','status',)

    def create(self, request, *args, **kwargs):
        self.serializer_class=ShopOrderSerializer
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        serializer = ShopOrderOutSerializer(serializer.instance)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=201, headers=headers)

    @list_route(methods=['GET'])
    def test_stock(self,request):
        request.user=User.objects.get(id=1)
        addr=Address.objects.get(id=1)
        cart=ShopCart.objects.get(id=1)
        data={
            "addr": addr.id,  # 收货地址的id
            "item_list": [cart.id,],
        }
        self.serializer_class=ShopOrderSerializer
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        return Response('ok')